package com.ssy.lingxi.message.serviceimpl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.message.entity.MainMessage;
import com.ssy.lingxi.message.entity.MemberMessage;
import com.ssy.lingxi.message.enums.CommonBooleanEnum;
import com.ssy.lingxi.message.enums.MessageTypeEnum;
import com.ssy.lingxi.message.repository.MainMessageRepository;
import com.ssy.lingxi.message.repository.MemberMessageRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 会员消息服务实现类
 * @author yzc
 * @version 2.0.0
 * @date 2020/10/27
 */
@Service
public class BaseMemberMessageService {

    @Resource
    private MemberMessageRepository memberMessageRepository;
    @Resource
    private MainMessageRepository mainMessageRepository;

    // ========平台发送/接收消息相关参数======start
    protected static Long MSG_PF_SEND_MEMBER_ID = 0L;
    protected static Long MSG_PF_SEND_ROLE_ID = 0L;
    protected static Long MSG_PF_REC_MEMBER_ID = 0L;
    protected static Long MSG_PF_REC_ROLE_ID = 0L;
    protected static Long MSG_PF_REC_USER_ID = 0L;
    // ========平台发送/接收消息相关参数======end

    /**
     * 拉取平台消息
     * 平台新增平台消息 --写入--> mainMessage表
     * mainMessage表 --拉取--> memberMessage表 --读取--> 展示消息
     * @param recMemberId 接收会员id
     * @param recRoleId 接收角色id
     * @param recUserId 接收用户id
     */
    protected void basePullMainMessage(Long recMemberId, Long recRoleId, Long recUserId) {
        // 查询所有主消息
        List<MainMessage> mainMessageList = mainMessageRepository.findAllByTypeAndExpireGreaterThan(MessageTypeEnum.PLATFORM.getCode(), System.currentTimeMillis());
        // 查询已拉取的主消息
        List<Long> allMessageIds = mainMessageList.stream().map(MainMessage::getId).collect(Collectors.toList());
        List<MemberMessage> memberMessageList = memberMessageRepository.findAllByRecMemberIdAndRecRoleIdAndMainMessageIdIn(recMemberId, recRoleId, allMessageIds);
        // 筛选未填充的主消息
        List<Long> messageIds = memberMessageList.stream().map(MemberMessage::getMainMessageId).collect(Collectors.toList());
        List<MainMessage> resultMessageList = mainMessageList.stream().filter(e -> !messageIds.contains(e.getId())).collect(Collectors.toList());

        // 分发主消息
        if (!CollectionUtils.isEmpty(resultMessageList)) {
            List<MemberMessage> saveMemberMessage = resultMessageList.stream()
                    .filter(e -> JSONUtil.toBean(e.getTarget(), new TypeReference<List<Long>>() {
                    }, false).contains(recRoleId))
                    .map(e -> {
                        MemberMessage memberMessage = new MemberMessage();
                        memberMessage.setMainMessageId(e.getId());
                        memberMessage.setSendMemberId(MSG_PF_SEND_MEMBER_ID);
                        memberMessage.setSendRoleId(MSG_PF_SEND_ROLE_ID);
                        memberMessage.setRecMemberId(recMemberId);
                        memberMessage.setRecRoleId(recRoleId);
                        memberMessage.setRecUserId(recUserId);
                        memberMessage.setStatus(CommonBooleanEnum.NO.getCode());
                        memberMessage.setDeleted(CommonBooleanEnum.NO.getCode());
                        memberMessage.setType(MessageTypeEnum.PLATFORM.getCode());
                        memberMessage.setTitle(e.getTitle());
                        memberMessage.setContent(e.getContent());
                        memberMessage.setUrl(e.getUrl());
                        memberMessage.setSendTime(e.getCreateTime());
                        memberMessage.setCreateTime(System.currentTimeMillis());

                        return memberMessage;
                    }).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(saveMemberMessage)) {
                memberMessageRepository.saveAll(saveMemberMessage);
            }
        }
    }

    protected String messageFormat(String template, List<String> params) {
        List<String> list = Optional.ofNullable(params)
                .map(l -> l.stream().map(e -> StringUtils.defaultIfEmpty(e, "")).collect(Collectors.toList()))
                .orElse(new ArrayList<>());
        return MessageFormat.format(template, list.toArray());
    }

    protected String urlFormat(String url, List<String> params) {
        if (!StringUtils.contains(url, "{0}")) {
            return url;
        }
        List<String> list = Optional.ofNullable(params)
                .map(l -> l.stream().map(e -> StringUtils.defaultIfEmpty(e, "")).collect(Collectors.toList()))
                .orElse(new ArrayList<>());
        return MessageFormat.format(url, list.toArray());
    }
}
